package myapp.DAO;

import java.util.ArrayList;

import myapp.DTO.CategoryDTO;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;

public class CategoryDAO extends DataProvider{
	private final String url = "Category/";
	
	public ArrayList<CategoryDTO> getAllCategories(){
		Log.i("CategoryDAO", "[getAllCategories]");
		String strResponse = requestGET(dbBaseHost + url);
		
		return parseJSONResponToArr(strResponse);
	}
	
	public CategoryDTO getCategory(int id){
		String response = requestGET(dbBaseHost + url + id);
		return parseJSONResponToObj(response);
	}
	
	private CategoryDTO parseJSONResponToObj(String jsonResponse){
		JSONObject json = null;		
		Log.i("CategoryDAO", "[parseJSON] jsonStr: " + jsonResponse);
		
		try {
			json = new JSONObject(jsonResponse);
			Log.i("CategoryDAO", "[parseJSON] json = " + json.toString());
		} catch (Exception e) {
			// TODO: handle exception
			Log.i("CategoryDAO", "[parseJSON] Exception: " + e.getMessage());
		}
		if (json != null)
			return jsonToCategoryDTO(json);
		return null;
	}
	
	private ArrayList<CategoryDTO> parseJSONResponToArr(String jsonResponse){
		JSONArray jsons;
		ArrayList<CategoryDTO> arr = new ArrayList<CategoryDTO>();
		
		Log.i("CategoryDAO", "[parseJSONArr] jsonStr: " + jsonResponse);
		
		try {
			jsons = new JSONArray(jsonResponse);
			Log.i("CategoryDAO", "[parseJSONArr] jsonsLength = " + jsons.length());
			
			for (int i=0; i<jsons.length(); i++){
				arr.add(jsonToCategoryDTO(jsons.getJSONObject(i)));
			}						
		} catch (Exception e) {
			// TODO: handle exception
			Log.i("CategoryDAO", "[parseJSONArr] Exception: " + e.getMessage());
		}		
		
		return arr;
	}
	
	private CategoryDTO jsonToCategoryDTO(JSONObject json){
		int id = -1;
		String name = null;
		try {
			id = json.getInt("Id");
			name = json.getString("CategoryName");
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
				
		return new CategoryDTO(id, name);
	}
}
